﻿#include <QColorDialog>
#include <QFileInfo>
#include <QFileDialog>
#include <QMessageBox>
#include "CLogCfgDlg.h"
#include "CLogMng.h"

CLogCfgDlg::CLogCfgDlg(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
	this->setWindowTitle(QString::fromLocal8Bit("配置"));
	initConnect();
	initUI();
	setUI();
}

CLogCfgDlg::~CLogCfgDlg()
{}

void CLogCfgDlg::slotSave()
{
	// 保存配置到CLogMng
	CLogMng& logMng = CLogMng::instance();

	// 基础配置
	logMng.m_isShowLimit = ui.checkBoxIsShowLimit->isChecked();
	logMng.m_showLimit = ui.lineEditShowLimit->text().toInt();
	logMng.m_showDescend = ui.radioButtonReverse->isChecked();
	logMng.m_tableGridColor = QColor(ui.lineEditTableGridColor->text());
	logMng.m_tableBackColor = QColor(ui.lineEditTableBackColor->text());

	logMng.m_mapLogLevelConfigs.clear();
	// 日志等级配置
	for (int i = 0; i < ui.tableWidget->rowCount(); i++)
	{
		// 获取ID
		QTableWidgetItem* itemID = ui.tableWidget->item(i, 0);
		if (!itemID) continue;

		int id = itemID->text().toInt();
		SLogLevelConfig config;

		config.id = id;
		// 获取描述
		QTableWidgetItem* itemDesc = ui.tableWidget->item(i, 1);
		if (itemDesc) config.desc = itemDesc->text();

		// 文本颜色和背景颜色从按钮获取
		QWidget* widgetTextColor = ui.tableWidget->cellWidget(i, 2);
		if (widgetTextColor)
		{
			QPushButton* btn = qobject_cast<QPushButton*>(widgetTextColor);
			if (btn) config.textColor = btn->property("color").value<QColor>();
		}

		QWidget* widgetBackColor = ui.tableWidget->cellWidget(i, 3);
		if (widgetBackColor)
		{
			QPushButton* btn = qobject_cast<QPushButton*>(widgetBackColor);
			if (btn) config.backColor = btn->property("color").value<QColor>();
		}

		// 图标路径从按钮获取
		QWidget* widgetIconPath = ui.tableWidget->cellWidget(i, 4);
		if (widgetIconPath)
		{
			QPushButton* btn = qobject_cast<QPushButton*>(widgetIconPath);
			if (btn) config.iconPath = btn->property("iconPath").toString();
		}
		logMng.m_mapLogLevelConfigs.insert(id,config);
	}

	// 保存配置到文件
	logMng.saveConfig();

	QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("配置保存成功"));
	this->close();
}

void CLogCfgDlg::slotClose()
{
	this->close();
}

void CLogCfgDlg::slotColorGrid()
{
	// 弹出颜色选择对话框
	QColor color = QColorDialog::getColor(QColor(ui.lineEditTableBackColor->text()), this, QString::fromLocal8Bit("选择颜色"));

	// 如果用户选择了颜色（没有点击取消）
	if (color.isValid())
	{
		ui.lineEditTableGridColor->setText(color.name());
		ui.lineEditTableGridColor->setStyleSheet(QString("QLineEdit { background-color: %1;color:%2 }")
			.arg(color.name())
			.arg(getContrastColor(color).name()));
	}
}

void CLogCfgDlg::slotColorBack()
{
	// 弹出颜色选择对话框
	QColor color = QColorDialog::getColor(QColor(ui.lineEditTableBackColor->text()), this, QString::fromLocal8Bit("选择颜色"));

	// 如果用户选择了颜色（没有点击取消）
	if (color.isValid())
	{
		ui.lineEditTableBackColor->setText(color.name());
		ui.lineEditTableBackColor->setStyleSheet(QString("QLineEdit { background-color: %1;color:%2 }")
			.arg(color.name())
			.arg(getContrastColor(color).name()));
	}
}

void CLogCfgDlg::slotTableTextColorClicked()
{
	QPushButton* button = qobject_cast<QPushButton*>(sender());
	if (!button) return;

	QColor currentColor = button->property("color").value<QColor>();
	QColor color = QColorDialog::getColor(currentColor, this, QString::fromLocal8Bit("选择文本颜色"));

	if (color.isValid())
	{
		// 更新按钮样式
		QString style = QString("QPushButton { background-color: %1; color: %2; border: 1px solid gray; }")
			.arg(color.name())
			.arg(getContrastColor(color).name());
		button->setStyleSheet(style);
		button->setText(color.name());
		button->setProperty("color", color);
	}
}

void CLogCfgDlg::slotTableBackColorClicked()
{
	QPushButton* button = qobject_cast<QPushButton*>(sender());
	if (!button) return;

	QColor currentColor = button->property("color").value<QColor>();
	QColor color = QColorDialog::getColor(currentColor, this, QString::fromLocal8Bit("选择背景颜色"));

	if (color.isValid())
	{
		// 更新按钮样式
		QString style = QString("QPushButton { background-color: %1; color: %2; border: 1px solid gray; }")
			.arg(color.name())
			.arg(getContrastColor(color).name());
		button->setStyleSheet(style);
		button->setText(color.name());
		button->setProperty("color", color);
	}
}

void CLogCfgDlg::slotTableIconClicked()
{
	QPushButton* button = qobject_cast<QPushButton*>(sender());
	if (!button) return;

	QString currentPath = button->property("iconPath").toString();
	QString filePath = QFileDialog::getOpenFileName(this,
		QString::fromLocal8Bit("选择图标文件"),
		QFileInfo(currentPath).path(),
		"Image Files (*.png *.jpg *.bmp *.ico)");

	if (!filePath.isEmpty())
	{
		// 设置按钮图标
		QIcon icon(filePath);
		if (!icon.isNull())
		{
			button->setIcon(icon);
			button->setText(QFileInfo(filePath).fileName());
			button->setProperty("iconPath", filePath);
		}
		else
		{
			QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("无法加载图标文件"));
		}
	}
}

void CLogCfgDlg::slotAdd()
{
	int nRow = ui.tableWidget->rowCount();
	ui.tableWidget->setRowCount(ui.tableWidget->rowCount()+1);
	// 日志等级ID
	QTableWidgetItem *itemID = new QTableWidgetItem();
	itemID->setTextAlignment(Qt::AlignCenter);
	ui.tableWidget->setItem(nRow, 0, itemID);

	// 描述（可编辑）
	QTableWidgetItem *itemDesc = new QTableWidgetItem();
	itemDesc->setTextAlignment(Qt::AlignCenter);
	ui.tableWidget->setItem(nRow, 1, itemDesc);

	// 文本颜色 - 使用按钮
	QPushButton* btnTextColor = new QPushButton("#FFFFFF");
	btnTextColor->setProperty("color", QColor("#FFFFFF"));
	QString textColorStyle = QString("QPushButton { background-color: %1; color: %2; border: 1px solid gray; }")
		.arg("#FFFFFF")
		.arg(getContrastColor(QColor("#FFFFFF")).name());
	btnTextColor->setStyleSheet(textColorStyle);
	connect(btnTextColor, &QPushButton::clicked, this, &CLogCfgDlg::slotTableTextColorClicked);
	ui.tableWidget->setCellWidget(nRow, 2, btnTextColor);

	// 背景颜色 - 使用按钮
	QPushButton* btnBackColor = new QPushButton(QColor("#FFFFFF").name());
	btnBackColor->setProperty("color", QColor("#FFFFFF"));
	QString backColorStyle = QString("QPushButton { background-color: %1; color: %2; border: 1px solid gray; }")
		.arg(QColor("#FFFFFF").name())
		.arg(getContrastColor(QColor("#FFFFFF")).name());
	btnBackColor->setStyleSheet(backColorStyle);
	connect(btnBackColor, &QPushButton::clicked, this, &CLogCfgDlg::slotTableBackColorClicked);
	ui.tableWidget->setCellWidget(nRow, 3, btnBackColor);

	// 图标路径 - 使用按钮
	QPushButton* btnIcon = new QPushButton(":/icon/Running.png");
	btnIcon->setProperty("iconPath", ":/icon/Running.png");
	QIcon icon(":/icon/Running.png");
	btnIcon->setIcon(icon);
	btnIcon->setStyleSheet("QPushButton { text-align: left; padding: 5px; }");
	connect(btnIcon, &QPushButton::clicked, this, &CLogCfgDlg::slotTableIconClicked);
	ui.tableWidget->setCellWidget(nRow, 4, btnIcon);
}

void CLogCfgDlg::slotDelete()
{
	int nCurrRow = ui.tableWidget->currentRow();
	if (nCurrRow > 0)
	{
		ui.tableWidget->removeRow(nCurrRow);
	}
	else
	{
		QMessageBox::warning(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("请先选择需要删除的行"));
	}
}

void CLogCfgDlg::initConnect()
{
	connect(ui.pushButtonSave, &QPushButton::clicked, this, &CLogCfgDlg::slotSave);
	connect(ui.pushButtonClose, &QPushButton::clicked, this, &CLogCfgDlg::slotClose);
	connect(ui.pushButtonTableGridColor, &QPushButton::clicked, this, &CLogCfgDlg::slotColorGrid);
	connect(ui.pushButtonTableBackColor, &QPushButton::clicked, this, &CLogCfgDlg::slotColorBack);
	connect(ui.pushButtonAdd, &QPushButton::clicked, this, &CLogCfgDlg::slotAdd);
	connect(ui.pushButtonDelete, &QPushButton::clicked, this, &CLogCfgDlg::slotDelete);
}

void CLogCfgDlg::initUI()
{
	QStringList headers;
	headers << QString::fromLocal8Bit("日志等级") << QString::fromLocal8Bit("描述") << QString::fromLocal8Bit("文本颜色") << QString::fromLocal8Bit("背景颜色")
		<< QString::fromLocal8Bit("图标路径");
	ui.tableWidget->setColumnCount(5);
	ui.tableWidget->setHorizontalHeaderLabels(headers);
	ui.tableWidget->setColumnWidth(0, 100);
	ui.tableWidget->setColumnWidth(1, 100);
	ui.tableWidget->setColumnWidth(2, 100);
	ui.tableWidget->setColumnWidth(3, 100);
	ui.tableWidget->setColumnWidth(4, 200);
	ui.tableWidget->setRowCount(CLogMng::instance().m_mapLogLevelConfigs.size());
	ui.tableWidget->verticalHeader()->setVisible(false);
	ui.tableWidget->horizontalHeader()->setStretchLastSection(true);
}

void CLogCfgDlg::setUI()
{
	CLogMng& logMng=CLogMng::instance();
	//基础配置部分
	if (logMng.m_isShowLimit)
	{
		ui.checkBoxIsShowLimit->setChecked(true);
	}
	else
	{
		ui.checkBoxIsShowLimit->setChecked(false);
	}
	ui.lineEditShowLimit->setText(QString::number(logMng.m_showLimit));
	
	if (logMng.m_showDescend)
	{
		ui.radioButtonReverse->setChecked(true);
		ui.radioButtonSequential->setChecked(false);
	}
	else
	{
		ui.radioButtonReverse->setChecked(false);
		ui.radioButtonSequential->setChecked(true);
	}

	ui.lineEditTableGridColor->setText(logMng.m_tableGridColor.name());
	ui.lineEditTableGridColor->setStyleSheet(QString("QLineEdit { background-color: %1;color:%2 }")
		.arg(logMng.m_tableGridColor.name())
		.arg(getContrastColor(logMng.m_tableGridColor).name()));
	ui.lineEditTableBackColor->setText(logMng.m_tableBackColor.name());
	ui.lineEditTableBackColor->setStyleSheet(QString("QLineEdit { background-color: %1;color:%2 }")
		.arg(logMng.m_tableBackColor.name())
		.arg(getContrastColor(logMng.m_tableBackColor).name()));
	//日志等级配置相关
	int i = 0;
	for (auto itor = logMng.m_mapLogLevelConfigs.begin(); itor != logMng.m_mapLogLevelConfigs.end(); itor++)
	{
		SLogLevelConfig config = itor.value();
		// 日志等级ID
		QTableWidgetItem *itemID = new QTableWidgetItem(QString::number(config.id));
		itemID->setTextAlignment(Qt::AlignCenter);
		ui.tableWidget->setItem(i, 0, itemID);

		// 描述（可编辑）
		QTableWidgetItem *itemDesc = new QTableWidgetItem(config.desc);
		itemDesc->setTextAlignment(Qt::AlignCenter);
		ui.tableWidget->setItem(i, 1, itemDesc);

		// 文本颜色 - 使用按钮
		QPushButton* btnTextColor = new QPushButton(config.textColor.name());
		btnTextColor->setProperty("color", config.textColor);
		QString textColorStyle = QString("QPushButton { background-color: %1; color: %2; border: 1px solid gray; }")
			.arg(config.textColor.name())
			.arg(getContrastColor(config.textColor).name());
		btnTextColor->setStyleSheet(textColorStyle);
		connect(btnTextColor, &QPushButton::clicked, this, &CLogCfgDlg::slotTableTextColorClicked);
		ui.tableWidget->setCellWidget(i, 2, btnTextColor);

		// 背景颜色 - 使用按钮
		QPushButton* btnBackColor = new QPushButton(config.backColor.name());
		btnBackColor->setProperty("color", config.backColor);
		QString backColorStyle = QString("QPushButton { background-color: %1; color: %2; border: 1px solid gray; }")
			.arg(config.backColor.name())
			.arg(getContrastColor(config.backColor).name());
		btnBackColor->setStyleSheet(backColorStyle);
		connect(btnBackColor, &QPushButton::clicked, this, &CLogCfgDlg::slotTableBackColorClicked);
		ui.tableWidget->setCellWidget(i, 3, btnBackColor);

		// 图标路径 - 使用按钮
		QPushButton* btnIcon = new QPushButton(QFileInfo(config.iconPath).fileName());
		btnIcon->setProperty("iconPath", config.iconPath);
		if (!config.iconPath.isEmpty() && QFile::exists(config.iconPath))
		{
			QIcon icon(config.iconPath);
			btnIcon->setIcon(icon);
		}
		btnIcon->setStyleSheet("QPushButton { text-align: left; padding: 5px; }");
		connect(btnIcon, &QPushButton::clicked, this, &CLogCfgDlg::slotTableIconClicked);
		ui.tableWidget->setCellWidget(i, 4, btnIcon);

		i++;
	}
}

QColor CLogCfgDlg::getContrastColor(const QColor& color) const
{
	// 计算颜色的亮度
	double brightness = (0.299 * color.red() + 0.587 * color.green() + 0.114 * color.blue()) / 255;
	return brightness > 0.5 ? Qt::black : Qt::white;
}
